package com.lixw.langchain.config;

import com.lixw.langchain.service.ChatAssistant;
import com.lixw.langchain.service.ChatMemoryAssistant;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.memory.chat.TokenWindowChatMemory;
import dev.langchain4j.model.TokenCountEstimator;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiTokenCountEstimator;
import dev.langchain4j.service.AiServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName: LLMConfig
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/8/22 18:43
 **/
@Configuration
public class LLMConfig {
    @Bean
    public ChatModel qwenChatModel() {
        return OpenAiChatModel.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(System.getenv("QWEN_API_KEY"))
                .modelName("qwen-plus")
                .build();
    }

    @Bean
    public ChatAssistant qWenChatAssistant() {
        return AiServices.create(ChatAssistant.class, qwenChatModel());
    }

    @Bean
    public ChatMemoryAssistant chatMessageWindowChatMemory(){
        return AiServices.builder(ChatMemoryAssistant.class)
                .chatModel(qwenChatModel())
                .chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(3))
                .build();
    }

    @Bean
    public ChatMemoryAssistant chatTokenWindowChatMemory(){
        TokenCountEstimator openAiTokenizer = new OpenAiTokenCountEstimator("gpt-4");
        return AiServices.builder(ChatMemoryAssistant.class)
                .chatModel(qwenChatModel())
                .chatMemoryProvider(memoryId -> TokenWindowChatMemory.withMaxTokens(1000, openAiTokenizer))
                .build();
    }

}